package com.btpn.custody.security.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.btpn.custody.dao.IUser;
import com.btpn.custody.entity.User;

public class CustomAuthenticationManager implements AuthenticationManager {

	private final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IUser userDao;

	@Value("${ldap.ip}")String ip;
	@Value("${ldap.port}")String port;
	@Value("${ldap.domain}")String domain;
	@Value("${ldap.bypass}")Boolean bypass;
	
	public Authentication authenticate(Authentication auth)	throws AuthenticationException {

		if(StringUtils.isBlank((String) auth.getPrincipal()) || StringUtils.isBlank((String) auth.getCredentials())){
			throw new BadCredentialsException("Invalid username/password");
		}
		
		// database
		User user = userDao.get(auth.getName());	
		if (user==null) {
			LOG.error("User does not exists!");
			throw new BadCredentialsException("User does not exists");
		}
		if (!user.isEnabled()) {
			LOG.error("User does not enabled!");
			throw new DisabledException("User disabled");
		}
		
		// for user with NULL groupRole
		if (user.getGroupRole()==null) {
			LOG.error("User dont have GroupRole!");
			throw new DisabledException("Undefine GroupRole for this user");
		}
		
		// for first login
		if (bypass) {
			LOG.info("By pass login : {} as {}", auth.getName(), user.getGroupRole().getRoles());
			return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), getAuthorities(user));
		}
		
		LOG.debug("Performing custom authentication: ldap://{}:{}", ip, port);
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, 	"com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, 				"ldap://" + ip + ":" + port);
		env.put(Context.SECURITY_AUTHENTICATION, 	"simple");
		env.put(Context.SECURITY_PRINCIPAL, 		auth.getName() + domain);
		env.put(Context.SECURITY_CREDENTIALS, 		auth.getCredentials().toString());	
		try {
			DirContext ctx = new InitialDirContext(env);
			ctx.close();
			
			LOG.debug("User details LDAP are good and ready to go");
			return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), getAuthorities(user));
		} catch (Exception e) {
			LOG.debug("", e);
			throw new BadCredentialsException("Username or password invalid");
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Collection<GrantedAuthority> getAuthorities(User user) {
		List list = new ArrayList<GrantedAuthorityImpl>();
		for (Iterator<String> i = user.getGroupRole().getRoles().iterator(); i.hasNext();) {
			list.add(new GrantedAuthorityImpl(i.next()));
		}

		return (ArrayList<GrantedAuthority>) list;
	} 
}